package com.github.winyiwin.matrix.web.exception.handler;

import com.alibaba.fastjson.JSON;
import com.github.matrix.common.resp.BaseResult;
import com.github.matrix.common.resp.BaseResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class DefaultExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseResult handleValidException(MethodArgumentNotValidException e) {
        log.warn("参数绑定异常:{}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError)->{
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        BaseResult baseResult = new BaseResult();
        baseResult.setCode(BaseResultCodeEnum.FAILED.getCode());
        baseResult.setMessage("请求参数绑定异常");
        baseResult.setExtraMessage(JSON.toJSONString(errorMap));
        baseResult.setTraceId(TraceContext.traceId());
        return baseResult;
    }

    @ExceptionHandler(value = {IllegalArgumentException.class})
    public BaseResult illegalArgumentException(IllegalArgumentException e) {
        log.warn("参数校验异常:{}", e.getMessage());
        BaseResult baseResult = new BaseResult();
        baseResult.setCode(BaseResultCodeEnum.FAILED.getCode());
        baseResult.setMessage("请求参数校验异常");
        baseResult.setExtraMessage(e.getMessage());
        baseResult.setTraceId(TraceContext.traceId());
        return baseResult;
    }



    @ExceptionHandler({Exception.class})
    public BaseResult exceptionHandler(HttpServletRequest request, Exception e) {
        log.error(e.getMessage(), e);
        return new BaseResult(HttpStatus.INTERNAL_SERVER_ERROR.value(),"系统异常", TraceContext.traceId(), e.getMessage(), null);
    }

}
